package services

import (
	"fmt"
	"github.com/goravel/framework/facades"
	"goravel/app/models"
	"goravel/app/types"
)

const (
	MaxDeep     = 4
	CacheKeyAll = "menus:all"
)

type MenuService struct {
	DBService
}

func NewMenuService() *MenuService {
	return &MenuService{}
}

func (s *MenuService) CacheAll() {
	menus, err := s.GetChildren(0, 3)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", menus)
	err = facades.Cache().Put(CacheKeyAll, menus, 0)
	if err != nil {
		panic(err)
	}
}

func (s *MenuService) GetChildren(parentId int, deep int) ([]types.SysMenuListResp, error) {
	var dao []models.SysMenu
	var vo []types.SysMenuListResp
	var err error
	err = facades.Orm().Query().Model(&dao).Where("parent_id", parentId).Find(&vo)
	if err != nil {
		return nil, err
	}
	if deep > MaxDeep {
		deep = MaxDeep
	}
	if deep <= 0 {
		return vo, nil
	}
	if len(vo) == 0 {
		return vo, nil
	}
	for index, menuResp := range vo {
		children, err := s.GetChildren(int(menuResp.Id), deep-1)
		if err != nil {
			vo[index].Children = nil
		}
		vo[index].Children = children
	}
	return vo, nil
}
